package org.leonos.utils;

import java.util.List;
import java.util.Map;

/**
 * 封装sql查询条件
 * @author hai
 *
 */
public class SqlUtil {

	
	/**
	 * 根据传参封装参数
	 * @param HQL
	 * 				hql语句
	 * @param queryMap
	 * 				传的条件与值
	 * @param paramList
	 * 				参数
	 */
	public static void loadParam(StringBuilder HQL,Map<String, Object> queryMap,List<Object> paramList){
		if(Utils.isNotNull(queryMap)){
			StringBuilder order = new StringBuilder();
			for (Map.Entry<String, Object> entry : queryMap.entrySet()) {
				String key = entry.getKey();
				if(key.contains("(")){ //表示有不用粘结的数据"()"
					HQL.append(" and ");
					HQL.append(key);
				}else if("orderby".equals(key)){//表示有排序的
					order.append(" order by ");
					order.append(entry.getValue());
					order.append(" ");
				}else{
					if(Utils.isNotNull(entry.getValue())){
						int index = key.lastIndexOf("_");
						if(index > 0){
							String name = key.substring(0,index);
							String value = key.substring(index+1);
							HQL.append(" and ");
							HQL.append(name);
							HQL.append(" ");
							HQL.append(value);
							HQL.append(" ? ");
							if("like".equals(value)){
								paramList.add("%" + entry.getValue() + "%");
							}else{
								paramList.add(entry.getValue());
							}
						}
					}
				}
			}
			HQL.append(order);
		}
	}
	
}
